<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item>
        <el-button
          v-if="mCheck"
          icon="el-icon-delete"
          type="danger"
          @click="mDel"
        >{{ $t('delete') }}
        </el-button>
      </el-form-item>
      <el-form-item v-if="sensor.sensorId">
        <el-button
          icon="el-icon-plus"
          type="primary"
          @click="showAdd"
        >{{ $t('add') }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-cpu"
          type="primary"
          @click="gotoSensor()"
        >{{ $t('sensor') }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="openEvalTest"
        >{{ $t('test') + $t('script') }}
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="sensorId"
          @change="sensorChange"
        >
          <el-option
            v-for="item in sensorList"
            :key="item.sensorId"
            :label="$t('port')+':'+item.port + ' ['+item.sensorName+']'"
            :value="item.sensorId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="name"
          clearable
          :placeholder="$t('name')"
          @change="listExplain"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="listExplain">{{ $t('search') }}</el-button>
      </el-form-item>
    </el-form>

    <el-table
      ref="explainTable"
      highlight-current-row
      :data="explainList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="rankNumber" :label="$t('rankNumber')" width="50" />
      <el-table-column width="30">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.iconUrl"
            style="width: 20px;height: 20px;margin-top: 5px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" :label="$t('name')" />
      <el-table-column prop="remark" :label="$t('remark')" />
      <el-table-column prop="type" :label="$t('type')" width="60" :formatter="formatExplainType" />
      <el-table-column prop="value" :label="$t('value')" />
      <el-table-column prop="rawValue" :label="$t('raw')+$t('value')" />
      <el-table-column prop="unit" width="70" :label="$t('unit')" />
      <el-table-column prop="updateFrequency" :label="$t('frequency')" :formatter="formatterSeconds" />
      <!--      <el-table-column :label="$t('device')+$t('linkage')" width="115" >-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-switch-->
      <!--            v-model="scope.row.canDeviceLinkage"-->
      <!--            @change="canDeviceLinkage(scope.row)"-->
      <!--          />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column :label="$t('hidden')" width="115">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.hidden"
            @change="hidden(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('filter')+$t('repeat')" width="115">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.filterRepeat"
            @change="filterRepeat(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('function')" width="280">
        <template slot-scope="scope">
          <el-button
            v-if="!scope.row.templateEvalId"
            type="text"
            icon="el-icon-first-aid-kit"
            @click="evalEdit(scope.row)"
          >{{ $t('script') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-warning-outline"
            @click="warmSet(scope.row)"
          >{{ $t('warn') }}
          </el-button>
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="edit(scope.row)"
          >{{ $t('edit') }}
          </el-button>
          <el-button
            style="color: #f56c6c"
            type="text"
            icon="el-icon-delete"
            @click="del(scope.row)"
          >{{ $t('delete') }}
          </el-button>
        </template>
      </el-table-column>
      <!--      <el-table-column  :label="$t('drag')" width="50">-->
      <!--        <template slot-scope="{}">-->
      <!--          <i class="el-icon-rank" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <el-dialog
      :visible.sync="dialogExplainFormVisible"
      top="15px"
    >
      <el-form
        label-width="120px"
        :model="explain"
      >
        <el-form-item :label="$t('name')">
          <el-autocomplete
            v-model="explain.name"
            :disabled="explain.explainId"
            :fetch-suggestions="nameSearch"
            @select="nameChange"
          />
        </el-form-item>
        <el-form-item :label="$t('keyName')">
          <el-autocomplete
            v-model="explain.keyName"
            :disabled="explain.explainId"
            :fetch-suggestions="keyNameSearch"
            @select="keyNameChange"
          />
        </el-form-item>
        <el-form-item :label="$t('remark')">
          <el-input v-model="explain.remark" />
        </el-form-item>
        <el-form-item :label="$t('raw')+$t('value')">
          <el-input v-model="explain.rawValue" />
        </el-form-item>
        <el-form-item :label="$t('unit')">
          <el-input v-model="explain.unit" />
        </el-form-item>
        <el-form-item :label="$t('count')">
          <el-input v-model="explain.count" />
        </el-form-item>
        <el-form-item :label="$t('number')">
          <el-input v-model="explain.num" />
        </el-form-item>
        <el-form-item :label="$t('max')+$t('value')">
          <el-input v-model="explain.maxRawVal" />
        </el-form-item>
        <el-form-item :label="$t('min')+$t('value')">
          <el-input v-model="explain.minRawVal" />
        </el-form-item>
        <el-form-item :label="$t('rankNumber')">
          <el-input v-model="explain.rankNumber" />
        </el-form-item>
        <el-form-item :label="$t('icon')">
          <el-input v-model="explain.iconUrl">
            <template slot="prepend">
              <el-image
                style="width: 20px;height: 20px;margin-top: 2px"
                :src="explain.iconUrl"
              />
            </template>
            <template slot="append">
              <i class="el-icon-caret-bottom" @click="choseIcon" />
            </template>
          </el-input>
          <div v-show="isIconOpen">
            <el-image
              v-for="(item,index) in iconList"
              :key="index"
              style="margin: 5px;cursor: pointer;width: 40px;height: 40px"
              :src="item.url"
              @click="changeIco(item.url,200145308)"
            />
          </div>
        </el-form-item>
        <el-form-item :label="$t('type')">
          <el-select v-model="explain.type">
            <el-option
              v-for="(item,index) in typeList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('script')">
          <el-select v-model="explain.templateEvalId">
            <el-option
              v-for="item in productTemplateExplainEvalList"
              :key="item.templateEvalId"
              :label="item.name"
              :value="item.templateEvalId"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('grade')">
          <el-input v-model="explain.grade" />
        </el-form-item>
        <el-form-item :label="$t('classify')">
          <el-tooltip
            class="item"
            effect="dark"
            content="空格分开多个数值用于图表分级,最多5级,最少2级，最好0开始"
            placement="top-start"
          >
            <el-input v-model="explain.classify" />
          </el-tooltip>
        </el-form-item>
        <el-form-item :label="$t('bind')+$t('setting')">
          <el-input v-model="explain.bindSetting" />
        </el-form-item>
        <el-form-item :label="$t('device')+$t('linkage')">
          <el-switch
            v-model="explain.canDeviceLinkage"
          />
        </el-form-item>
        <el-form-item :label="$t('hidden')">
          <el-switch
            v-model="explain.hidden"
          />
        </el-form-item>
        <el-form-item :label="$t('filter')+$t('repeat')">
          <el-switch
            v-model="explain.filterRepeat"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogExplainFormVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="addOrUpdate">{{ $t('confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="evalTitle"
      :visible.sync="dialogEvalFormVisible"
      top="15px"
    >
      <el-form
        v-if="dialogEvalFormVisible"
        label-width="120px"
      >
        <el-form-item label="$timeStamp">
          <el-input
            :value="explain.valueDate"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="$language">
          <el-input
            :value="language"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item v-for="(item,index) in explainList" :key="index" :label="'$'+item.keyName">
          <el-input
            :value="item.name+' [ '+item.rawValue+' -> '+item.value+' ] '"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item :label="$t('language')">
          <el-select v-model="explainEval.language">
            <el-option
              v-for="item in languageList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('rule')">
          <el-alert
            :closable="false"
            type="warning"
            title="映射的值自动注入(添加下划线前缀$),全局变量$res保存结果,不要return"
          />
          <el-alert
            :closable="false"
            type="warning"
            title="不支持单引号，请输入双引号"
          />
          <textarea ref="textarea" />
        </el-form-item>
        <el-form-item v-if="isTest" :label="$t('output')">
          <el-input
            v-model="explainEval.back"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEvalFormVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="testOrUpdateEvalScript">{{ $t('save') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="explain.name"
      :visible.sync="dialogExplainWarnFormVisible"
      width="1000px"
      top="50px"
    >
      <el-tabs>
        <el-tab-pane :label="$t('config')">
          <device-explain-config-warn v-if="dialogExplainWarnFormVisible" :explain-id="explain.explainId" />
        </el-tab-pane>
        <el-tab-pane :label="$t('warn')">
          <device-warn
            v-if="dialogExplainWarnFormVisible"
            :device-core="deviceCore"
            :port="port"
            :key-name="explain.keyName"
            :status="null"
          />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

  </div>
</template>
<script>
import {
  deleteExplain,
  deleteExplainList,
  getExplainEval,
  insertExplain,
  insertOrUpdateEval,
  listEvalLanguage,
  listExplain,
  updateExplain,
  updateExplainList
} from '@/api/iot/iotDeviceExplainApi'
import { listSensorIcon, listSensorWith } from '@/api/iot/iotDeviceSensorApi'
import { listProductTemplateExplain } from '@/api/iot/iotProductTemplateExplainApi'
import { testScript } from '@/api/iot/iotTestApi'
import { cancelNotice, formatDate, formatExplainType, listExplainType, successNotice } from '@/util/common'
import Sortable from 'sortablejs'
import DeviceExplainConfigWarn from '@/components/DeviceExplainConfigWarn'
import DeviceWarn from '@/components/DeviceWarn'
import { getLanguage } from '@/util/storage'
// 引入全局实例
import _CodeMirror from 'codemirror'

// 核心样式
import 'codemirror/lib/codemirror.css'
// 引入主题后还需要在 options 中指定主题才会生效
import 'codemirror/theme/cobalt.css'

// 需要引入具体的语法高亮库才会有对应的语法高亮效果
// codemirror 官方其实支持通过 /addon/mode/loadmode.js 和 /mode/meta.js 来实现动态加载对应语法高亮库
// 但 vue 貌似没有无法在实例初始化后再动态加载对应 JS ，所以此处才把对应的 JS 提前引入
import 'codemirror/mode/javascript/javascript.js'
import 'codemirror/mode/groovy/groovy'
import { listProductTemplateExplainEval } from '@/api/iot/iotProductTemplateExplainEvalApi'

// 尝试获取全局实例
const CodeMirror = window.CodeMirror || _CodeMirror

export default {
  name: 'Explain',
  components: {
    DeviceExplainConfigWarn,
    DeviceWarn
  },
  data() {
    return {
      language: getLanguage(),
      iconList: [],
      explainList: [],
      sensorList: [],
      sensor: {},
      sensorId: null,
      dialogExplainWarnFormVisible: false,
      dialogExplainFormVisible: false,
      dialogEvalFormVisible: false,
      explain: {},
      explainEval: {
        map: null,
        eval: null,
        language: null,
        back: null
      },
      productTemplateExplainList: [],
      isIconOpen: false,
      deviceCore: null,
      sensorName: null,
      deviceName: null,
      mList: [],
      mCheck: false,
      name: null,
      evalTitle: '',
      isTest: false,
      nameList: [],
      keyNameList: [],
      // 编辑器实例
      coder: null,
      languageList: [],
      productTemplateExplainEvalList: [],
      typeList: listExplainType(this)
    }
  },
  mounted() {
    const param = this.$route.query
    this.sensorId = param.sensorId ? parseInt(param.sensorId) : null
    this.deviceCore = param.deviceCore
    this.deviceName = param.deviceName
    this.sensorName = param.sensorName
    this.listEvalLanguage()
    this.listSensorWith()
    this.listProductTemplateExplain()
    listSensorIcon({}).then(res => {
      const { code } = res
      if (code === '200') {
        this.iconList = res.data
      }
    })
    this.setTagsViewTitle()
  },
  methods: {
    listProductTemplateExplainEval() {
      listProductTemplateExplainEval({
        templateId: this.explain.templateId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.productTemplateExplainEvalList = data
        } else {
          this.productTemplateExplainEvalList = []
        }
        this.productTemplateExplainEvalList.unshift({
          templateEvalId: 0,
          name: this.$t('empty')
        })
      })
    },
    listEvalLanguage() {
      listEvalLanguage().then(res => {
        const { code, data } = res
        const languageList = []
        if (code === '200') {
          data.forEach(item => {
            languageList.push({
              value: item,
              label: item
            })
          })
        }
        this.languageList = languageList
      })
    },
    hidden(item) {
      updateExplain({
        explainId: item.explainId,
        hidden: item.hidden
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listExplain()
      })
    },
    filterRepeat(item) {
      updateExplain({
        explainId: item.explainId,
        filterRepeat: item.filterRepeat
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listExplain()
      })
    },
    canDeviceLinkage(item) {
      updateExplain({
        explainId: item.explainId,
        canDeviceLinkage: item.canDeviceLinkage
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listExplain()
      })
    },
    warmSet(index) {
      this.explain = index
      this.dialogExplainWarnFormVisible = true
    },
    sensorChange() {
      this.sensorList.forEach(sensor => {
        if (this.sensorId === sensor.sensorId) {
          this.sensor = sensor
          const explainList = []
          if (this.name) {
            sensor.explainList.forEach(explain => {
              if (explain.name.indexOf(this.name) >= 0) {
                explainList.push(explain)
              }
            })
            this.explainList = explainList
          } else {
            this.explainList = sensor.explainList
          }
          this.$nextTick(() => {
            this.setSort()
          })
        }
      })
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    nameSearch(queryString, cb) {
      const nameList = this.nameList
      const results = queryString ? nameList.filter(this.createFilter(queryString)) : nameList
      cb(results)
    },
    keyNameSearch(queryString, cb) {
      const keyNameList = this.keyNameList
      const results = queryString ? keyNameList.filter(this.createFilter(queryString)) : keyNameList
      cb(results)
    },
    initEval() {
      // 初始化编辑器实例，传入需要被实例化的文本域对象和默认配置
      this.coder = CodeMirror.fromTextArea(this.$refs.textarea, {
        // 缩进格式
        tabSize: 2,
        // 主题，对应主题库 JS 需要提前引入
        theme: 'cobalt',
        // 显示行号
        lineNumbers: true,
        line: true
      })
      // 编辑器赋值
      this.coder.setValue(this.explainEval.eval)

      // 支持双向绑定
      this.coder.on('change', (coder) => {
        this.explainEval.eval = coder.getValue()

        if (this.$emit) {
          this.$emit('input', this.explainEval.eval)
        }
      })
    },
    openEvalTest() {
      const map = {}
      this.explainList.forEach(explain => {
        map[explain.keyName] = explain.rawValue
      })
      map['language'] = 'zh'
      map['timeStamp'] = 1609814186
      this.explain = {
        valueDate: 1609814186
      }
      this.evalTitle = this.$t('test')
      this.dialogEvalFormVisible = true
      this.isTest = true
      this.explainEval.eval = ''
      this.explainEval.map = map
      this.explainEval.language = 'javascript'
      const that = this
      this.$nextTick(() => {
        that.initEval()
      })
    },
    evalEdit(item) {
      this.explain = item
      this.isTest = false
      this.evalTitle = item.name
      getExplainEval({
        explainId: this.explain.explainId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.dialogEvalFormVisible = true
          if (data.eval) {
            this.explainEval.eval = data.eval
          } else {
            this.explainEval.eval = ''
          }
          if (data.language) {
            this.explainEval.language = data.language
          } else {
            this.explainEval.language = 'javascript'
          }
          const that = this
          this.$nextTick(() => {
            that.initEval()
          })
        }
      })
    },
    formatDate(time) {
      return formatDate(this, time)
    },
    formatterSeconds(item) {
      if (item.updateFrequency > 60) {
        return parseInt(item.updateFrequency / 60) + this.$t('minutes')
      } else {
        return item.updateFrequency + this.$t('seconds')
      }
    },
    mDel() {
      const that = this
      this.$confirm(this.$t('deletePrompt'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteExplainList({
            idList: that.mList
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
            }
            that.listExplain()
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    },
    handleSelectionChange(val) {
      const mList = []
      val.forEach(function(row) {
        mList.push(row.explainId)
      })
      this.mList = mList
      if (mList.length > 0) {
        this.mCheck = true
      } else {
        this.mCheck = false
      }
    },
    setTagsViewTitle() {
      this.tempRoute = Object.assign({}, this.$route)
      const route = Object.assign({}, this.tempRoute, {
        title: `${this.deviceName}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    changeIco(iconUrl) {
      this.isIconOpen = false
      this.explain.iconUrl = iconUrl
    },
    choseIcon() {
      if (this.isIconOpen) {
        this.isIconOpen = false
      } else {
        this.isIconOpen = true
      }
    },
    keyNameChange(item) {
      this.explain.keyName = item.value
      for (let i = 0; i < this.productTemplateExplainList.length; i++) {
        if (this.productTemplateExplainList[i].keyName === item.value) {
          this.explain.name = this.productTemplateExplainList[i].name
          this.explain.templateEvalId = this.productTemplateExplainList[i].templateEvalId
          this.explain.templateId = this.productTemplateExplainList[i].templateId
          this.explain.iconUrl = this.productTemplateExplainList[i].iconUrl
          this.explain.canDeviceLinkage = this.productTemplateExplainList[i].canDeviceLinkage
          this.explain.rawValue = this.productTemplateExplainList[i].value
          this.explain.type = this.productTemplateExplainList[i].type
          this.explain.hidden = this.productTemplateExplainList[i].hidden
          this.explain.rankNumber = this.productTemplateExplainList[i].rankNumber
          this.listProductTemplateExplainEval()
          break
        }
      }
    },
    nameChange(item) {
      this.explain.name = item.value
      for (let i = 0; i < this.productTemplateExplainList.length; i++) {
        if (this.productTemplateExplainList[i].name === item.value) {
          this.explain.keyName = this.productTemplateExplainList[i].keyName
          this.explain.templateEvalId = this.productTemplateExplainList[i].templateEvalId
          this.explain.templateId = this.productTemplateExplainList[i].templateId
          this.explain.iconUrl = this.productTemplateExplainList[i].iconUrl
          this.explain.canDeviceLinkage = this.productTemplateExplainList[i].canDeviceLinkage
          this.explain.rawValue = this.productTemplateExplainList[i].value
          this.explain.type = this.productTemplateExplainList[i].type
          this.explain.hidden = this.productTemplateExplainList[i].hidden
          this.explain.rankNumber = this.productTemplateExplainList[i].rankNumber
          this.listProductTemplateExplainEval()
          break
        }
      }
    },
    testOrUpdateEvalScript() {
      if (this.isTest) {
        testScript({
          eval: this.explainEval.eval,
          map: this.explainEval.map,
          language: this.explainEval.language
        }).then(res => {
          const { code, data } = res
          if (code === '200') {
            this.explainEval.back = data
          }
        })
      } else {
        insertOrUpdateEval({
          eval: this.explainEval.eval,
          language: this.explainEval.language,
          explainId: this.explain.explainId
        }).then(res => {
          const { code } = res
          if (code === '200') {
            this.dialogEvalFormVisible = false
            this.listExplain()
          }
        })
      }
    },
    listProductTemplateExplain() {
      listProductTemplateExplain({
        deviceCore: this.deviceCore
      }).then(res => {
        const { data, code } = res
        if (code === '200') {
          this.productTemplateExplainList = data
          const nameList = []
          const keyNameList = []
          data.forEach(item => {
            nameList.push({ value: item.name })
            keyNameList.push({ value: item.keyName })
          })
          this.nameList = nameList
          this.keyNameList = keyNameList
        } else {
          this.productTemplateExplainList = []
          this.nameList = []
          this.keyNameList = []
        }
      })
    },
    formatExplainType(item) {
      return formatExplainType(this, item.type)
    },
    setSort() {
      const el = this.$refs.explainTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData(dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.explainList.splice(evt.oldIndex, 1)[0]
          this.explainList.splice(evt.newIndex, 0, targetRow)
          const updateList = []
          for (let i = 0, j = this.explainList.length; i < j; i++) {
            const explain = this.explainList[i]
            const data = {
              rankNumber: i,
              explainId: explain.explainId
            }
            updateList.push(data)
          }

          updateExplainList({
            explainList: updateList
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(this)
              this.listExplain()
            }
          })
        }
      })
    },
    listExplain() {
      this.explainList = []
      listExplain({
        sensorId: this.sensor.sensorId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.explainList = data
          this.$nextTick(() => {
            this.setSort()
          })
        }
      })
    },
    listSensorWith() {
      listSensorWith({
        deviceCore: this.deviceCore,
        withExplain: true
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.sensorList = data
          let explainListRes
          if (this.sensorId) {
            data.forEach(sensor => {
              if (sensor.sensorId === this.sensorId) {
                this.sensor = sensor
                this.sensorId = this.sensor.sensorId
                explainListRes = sensor.explainList
              }
            })
          } else {
            this.sensor = data[0]
            this.sensorId = this.sensor.sensorId
            explainListRes = data[0].explainList
          }
          const explainList = []
          if (this.name) {
            explainListRes.forEach(explain => {
              if (explain.name.indexOf(this.name) >= 0) {
                explainList.push(explain)
              }
            })
            this.explainList = explainList
          } else {
            this.explainList = explainListRes
          }
          this.$nextTick(() => {
            this.setSort()
          })
        } else {
          this.sensorList = []
          this.sensor = {}
        }
      })
    },
    gotoSensor() {
      this.$router.push({
        path: '/device/sensor/' + this.deviceCore,
        query: { deviceCore: this.deviceCore, deviceName: this.deviceName }
      })
    },
    showAdd() {
      this.explain = {
        port: this.sensor.port,
        deviceCore: this.deviceCore,
        rawValue: '',
        hidden: false
      }
      this.dialogExplainFormVisible = true
    },
    addOrUpdate() {
      const json = {
        ...this.explain
      }
      if (!this.explain.explainId) {
        insertExplain(json).then(res => {
          const { code } = res
          if (code === '200') {
            this.dialogExplainFormVisible = false
          }
          this.listExplain()
        })
      } else {
        updateExplain(json).then(res => {
          const { code } = res
          if (code === '200') {
            this.dialogExplainFormVisible = false
          }
          this.listExplain()
        })
      }
    },
    edit(item) {
      this.explain = item
      this.dialogExplainFormVisible = true
      for (let i = 0; i < this.productTemplateExplainList.length; i++) {
        if (this.productTemplateExplainList[i].keyName === item.keyName) {
          // this.explain.templateEvalId = this.productTemplateExplainList[i].templateEvalId
          this.explain.templateId = this.productTemplateExplainList[i].templateId
          this.listProductTemplateExplainEval()
        }
      }
    },
    del(index) {
      const that = this
      this.$confirm(this.$t('delete') + index.name, this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(function() {
          deleteExplain({
            explainId: index.explainId
          }).then(res => {
            const { code } = res
            if (code === '200') {
              successNotice(that)
              that.listExplain()
            }
          })
        })
        .catch(function() {
          cancelNotice(that)
        })
    }
  }
}
</script>
